#include "../include/Acceptor.hpp"
#include <iostream>
    
namespace wd{

Acceptor::Acceptor(unsigned short port, const string & ip)
:_addr(port,ip)
,_listensock()
{
}

void Acceptor::ready(){
    setReuseAddr(true);
    setReusePort(true);
    bind();
    listen();
}

int Acceptor::accept(){
    int ret = ::accept(_listensock.fd(),nullptr,nullptr);
    if(ret < 0){
        perror("accept");
    }

    return ret;
}

void Acceptor::setReuseAddr(bool on){
    int value = on;
    int ret = setsockopt(_listensock.fd(),
                         SOL_SOCKET,
                         SO_REUSEADDR,
                         &value,
                         sizeof(value));
    if(ret < 0) {
        perror("setsockopt");
    }

}

void Acceptor::setReusePort(bool on){
    int value = on;
    int ret = setsockopt(_listensock.fd(),
                         SOL_SOCKET,
                         SO_REUSEPORT,
                         &value,
                         sizeof(value));
    if(ret < 0) {
        perror("setsockopt");
    }

}

void Acceptor::bind(){
    int ret = ::bind(_listensock.fd(),(const struct sockaddr*)_addr.get(),sizeof(_addr));
    if(ret < 0){
        perror("bind");
    }
}

void Acceptor::listen(){
    int ret = ::listen(_listensock.fd(),1000);  //?
    if(ret < 0){
        perror("listen");
    }
}
    
} //end of namespace wd
